#include <dicom/storage/local_cache.h>
#include <dicom/storage/encrypt.h>
#include <gwbase/base/util.h>
#include <gwbase/base/test_util.h>
#include <gwbase/base/test_harness.h>

using namespace dicom;

const std::string key =
    "defc580a5dccfd05a7f2b5433fea3283a5b962627189b17ec3a6ae5239462c17";

class LocalCacheTest {};

TEST(LocalCacheTest, EncryptFile) {
  const char* test_dir = "cache_test_dir";
  const std::string src_file = "1.dat";
  const std::string expect_out = "1.expect.dat";
  dicom::CreateDir(test_dir);
  LRUFileCache* c = NewLocalCache(test_dir, 1000);
  CreateTestFile("1.dat", 1, false, '\n');

  HashEntry hash1;
  dicom::ZipAndEncryptFile(key, src_file, expect_out, &hash1);

  HashEntry hash;
  LRUFileCache::Handle* h =
      dicom::SaveFileToCacheWithAES(c, src_file, "id1", key, &hash);
  EXPECT_TRUE(h != NULL);

  LOG_INFO << c->FilePath(h);

  CheckSameFile(c->FilePath(h), expect_out);
  delete c;
}

TEST(LocalCacheTest, Simple) {
  const char* test_dir = "cache_test_dir";
  dicom::CreateDir(test_dir);
  LRUFileCache* c = NewLocalCache(test_dir, 1000);
  CreateTestFile("1.dat", 500);

  c->Erase("1");
  c->Erase("2");

  LRUFileCache::Handle* h1;

  h1 =
      c->Insert("1", "1.dat", 500, "", "", FileInTmpDir::no, Sticky::removable);
  EXPECT_TRUE(h1 != NULL);
  c->Release(h1);

  CreateTestFile("2.dat", 600);
  h1 = c->Insert("2", "2.dat", 600, "", "", FileInTmpDir::no, Sticky::sticky);
  EXPECT_TRUE(h1 != NULL);
  c->Release(h1);

  h1 = c->Lookup("1");
  EXPECT_TRUE(h1 == NULL);

  CreateTestFile("3.dat", 500);
  h1 = c->Insert("3", "3.dat", 500, "", "", FileInTmpDir::no, Sticky::sticky);
  EXPECT_TRUE(h1 == NULL);

  delete c;
}

int main() { RunAllTests(); }
